08. 练习: TensorFlow 交叉熵

TensorFlow 中的交叉熵(Cross Entropy)

与 softmax 一样,TensorFlow 也有一个函数可以方便地帮我们实现交叉熵。

Cross entropy loss function 交叉熵损失函数

Cross entropy loss function 交叉熵损失函数

让我们把你从视频当中学到的知识,在 TensorFlow 中来创建一个交叉熵函数。创建一个交叉熵函数,你需要用到这两个新的函数:

Reduce Sum

x = tf.reduce_sum([1, 2, 3, 4, 5])  # 15

tf.reduce_sum() 函数输入一个序列,返回它们的和

Natural Log

x = tf.log(100)  # 4.60517

tf.log() 所做跟你所想的一样,它返回所输入值的自然对数。

练习

softmax_dataone_hot_encod_label 打印交叉熵

Start Quiz:

# Solution is available in the other "solution.py" tab
import tensorflow as tf

softmax_data = [0.7, 0.2, 0.1]
one_hot_data = [1.0, 0.0, 0.0]

softmax = tf.placeholder(tf.float32)
one_hot = tf.placeholder(tf.float32)

# TODO: Print cross entropy from session
# Quiz Solution
# Note: You can't run code in this tab
import tensorflow as tf

softmax_data = [0.7, 0.2, 0.1]
one_hot_data = [1.0, 0.0, 0.0]

softmax = tf.placeholder(tf.float32)
one_hot = tf.placeholder(tf.float32)

# ToDo: Print cross entropy from session
cross_entropy = -tf.reduce_sum(tf.multiply(one_hot, tf.log(softmax)))

with tf.Session() as sess:
    print(sess.run(cross_entropy, feed_dict={softmax: softmax_data, one_hot: one_hot_data}))